package com.chen.spider.config;

import com.chen.spider.dto.SpiderEntity;
import com.chen.spider.dto.SpiderMainPageEntity;
import com.chen.spider.service.SpiderService;
import lombok.SneakyThrows;
import org.apache.commons.collections.CollectionUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.JsonPathSelector;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 爬取类
 */
@Component
public class MyProcessor implements PageProcessor {
    List<String> urlList = new ArrayList<>();
    List<String> mainTitleList = new ArrayList<>();
    @Resource
    SpiderService spiderService;
    public static final String URL_LIST = "https://www.pkufh.com/Html/News/Columns/1064/[0-9]+.html";
    public static final String URL_POST = "https://www.pkufh.com/Html/News/Articles/[0-9]+.html";
    private static final String LIST_URL = "https://www.pkufh.com/PartialView/_Plugin/_GetArticleViewCount/[0-9]+?isPlus=True&r=[0-9]+";

    /*对当前站点的配置和封装  返回站点信息*/
    @Override
    public Site getSite() {
        return Site.me().setSleepTime(100);//.setRetryTimes(3)
    }

    /**
     * 方法一
     * 将数据存入两个表中的process  (函数主页面的链接标题存一个表[spiderMainPage]，子页面内容存一个表[spider])     使用时请将函数名修改为process
     *
     * @param page
     */
    @SneakyThrows
    public void process(Page page) {
        SpiderEntity spiderEntity = new SpiderEntity();
        SpiderMainPageEntity spiderMainPageEntity = new SpiderMainPageEntity();
        //列表页
        if (page.getUrl().regex(URL_LIST).match()) {
            urlList = page.getHtml().xpath("ul[@id=\"zoom\"]").links().regex(URL_POST).all();
            page.addTargetRequests(urlList);
            mainTitleList = page.getHtml().xpath("ul[@class=\"column_list tit_long\"]/li/a/text()").all();

            page.addTargetRequests(page.getHtml().links().regex(URL_LIST).all());    //没有这句话 只爬取当前页面，这个就是让符合的页面都进来，这样才能爬每个页面的详情列表页
            //文章详情页
        } else {
            String title = page.getHtml().xpath("[@class=\"Min\"]/h1/font/text()").toString();
            page.putField("title", title);

            String source = page.getHtml().xpath("span[@class=\"source\"]/text()").toString();
            page.putField("source", source);

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
            String time = page.getHtml().xpath("span[@class=\"time\"]/text()").toString().substring(5, 15);
            Date date = dateFormat.parse(time);  //解析字符串成日期    还有个方法是 df.format() 将日期按格式弄成字符串
            page.putField("time", time);

            String content = page.getHtml().xpath("div[@class=\"article_cont\"]/allText()").toString();
            page.putField("content", content);

            spiderEntity.setTitle(title);
            spiderEntity.setSource(source);
            spiderEntity.setCreateTime(date);
            spiderEntity.setContent(content);

        }
        if (spiderEntity.getTitle() == null) {
            page.setSkip(true);
        } else {
            page.putField("repo", spiderEntity);
        }
        if (urlList != null) {
            for (int i = 0; i < urlList.size(); i++) {
                spiderMainPageEntity.setHref(urlList.get(i));
                spiderMainPageEntity.setMainTitle(mainTitleList.get(i));
                page.putField("repo2", spiderMainPageEntity);
                if (spiderMainPageEntity.getHref() == null) {
                    page.setSkip(true);
                } else {
                    spiderService.insertMain(spiderMainPageEntity);  //这里要想不空指针 要在启动类加上注入的MyProcess 而不是new的
                }
            }
            urlList.clear();
        }

    }


    /**
     * 方法二 （参考了秦辉的思路）
     * 将数据存入一个表[spider]中的process函数        使用时请将函数名修改为process
     */

    public void process1(Page page) {
        MyProcessor m = new MyProcessor();
        SpiderEntity spiderEntity = new SpiderEntity();
        page.addTargetRequests(page.getHtml().links().regex("(https://www.pkufh.com/Html/News/Columns/1064/[0-9]+.html)").all()); //将所有符合的链接放入队列中
        urlList = page.getHtml().xpath("ul[@class=\"column_list tit_long\"]/li/a/@href").all();
        for (String url : urlList) {
            String newUrl = "https://www.pkufh.com" + url;  //内链接的url
            Document doc = m.getDocument(newUrl);
            Elements elements = doc.select("[class=Min]");//内链接页面文本的class
            String content = elements.get(0).text();//获取内链接的文本信息
            Elements elements1 = doc.select("[class=article_title]");//内链接标题部分
            String title = elements1.get(0).text();
            spiderEntity.setHref(newUrl);
            spiderEntity.setTitle(title);
            spiderEntity.setContent(content);
            page.putField("repo", spiderEntity);
        }
    }

    public Document getDocument(String url) {
        try {
            //5000是设置连接超时时间，单位ms
            return Jsoup.connect(url).timeout(5000).get();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }


}
